package com.edu.admin.filter;

import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.Serializable;

/**
 * 
 * @author Wangjiong
 * 
 */
@Component
public class SysAuthenticationEntryPoint implements AuthenticationEntryPoint, Serializable {

    private static final long serialVersionUID = -8970718410437077606L;

    @Override
    public void commence(HttpServletRequest request,
                         HttpServletResponse response,
                         AuthenticationException authException) throws IOException {
    	
    	HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse res = (HttpServletResponse) response;
		
    	String requestType = req.getHeader("X-Requested-With");
		if (!StringUtils.isEmpty(requestType) && requestType.equalsIgnoreCase("XMLHttpRequest")) {
			res.setStatus(200);
			res.setHeader("Content-Type","text/plain;charset=utf-8");
			String json = "{\"code\":" + 403 + ",\"msg\":\"" + "403 FORBIDDEN" + "\"}";
			res.getWriter().write(json);
			return;
		} else {
			res.sendRedirect(req.getContextPath() + "/login");
			return;
		}
    }
}
